from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from rest_framework import viewsets, filters
from django_filters.rest_framework import DjangoFilterBackend
from .models import AlarmRecord
from .serializers import AlarmRecordSerializer
from .filters import AlarmRecordFilter
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.db import transaction

class AlarmRecordViewSet(viewsets.ReadOnlyModelViewSet):
    """报警记录API视图集"""
    queryset = AlarmRecord.objects.all()
    serializer_class = AlarmRecordSerializer
    permission_classes = [IsAuthenticated]
    filterset_class = AlarmRecordFilter

    def get_queryset(self):
        """只返回当前用户的报警记录"""
        return AlarmRecord.objects.filter(
            Q(mqtt_subscription__created_by=self.request.user) |
            Q(opcua_subscription__created_by=self.request.user)
        ).select_related(
            'mqtt_subscription', 
            'mqtt_subscription__data_source',
            'opcua_subscription',
            'opcua_subscription__data_source',
            'mqtt_item'
        )

class AlarmListView(LoginRequiredMixin, ListView):
    """报警记录列表视图"""
    model = AlarmRecord
    template_name = 'alarms/alarm_list.html'
    context_object_name = 'alarms'
    paginate_by = 20

    def get_queryset(self):
        """只显示当前用户的报警记录，并应用过滤器"""
        queryset = AlarmRecord.objects.filter(
            Q(mqtt_subscription__created_by=self.request.user) |
            Q(opcua_subscription__created_by=self.request.user)
        ).select_related(
            'mqtt_subscription', 
            'mqtt_subscription__data_source',
            'opcua_subscription',
            'opcua_subscription__data_source',
            'mqtt_item',
            'acknowledged_by'
        ).order_by('-created_at')

        # 应用过滤器
        self.filterset = AlarmRecordFilter(self.request.GET, queryset=queryset)
        return self.filterset.qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = self.filterset
        return context

@require_POST
@login_required
def acknowledge_alarm(request):
    """处理报警确认"""
    try:
        with transaction.atomic():
            alarm_id = request.POST.get('alarm_id')
            note = request.POST.get('note', '').strip()
            
            alarm = AlarmRecord.objects.get(id=alarm_id)
            
            # 检查是否是自己的报警记录
            if not (alarm.mqtt_subscription and alarm.mqtt_subscription.created_by == request.user) and \
               not (alarm.opcua_subscription and alarm.opcua_subscription.created_by == request.user):
                return JsonResponse({
                    'success': False,
                    'message': '无权限确认此报警'
                })
            
            # 更新报警记录
            alarm.acknowledged = True
            alarm.acknowledged_by = request.user
            alarm.acknowledged_at = timezone.now()
            if note:
                alarm.note = note
            alarm.save()
            
            return JsonResponse({
                'success': True,
                'message': '报警已确认'
            })
            
    except AlarmRecord.DoesNotExist:
        return JsonResponse({
            'success': False,
            'message': '报警记录不存在'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': str(e)
        })
